package com.lagou.demo.factory;



import com.lagou.demo.service.ICheckAuthorityService;
import com.lagou.edu.mvcframework.annotations.LagouAutowired;
import com.lagou.edu.mvcframework.annotations.LagouSecurity;
import com.lagou.edu.mvcframework.annotations.LagouService;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;


/**
 * 代理对象工厂：生成代理对象的
 */
@LagouService
public class ProxyFactory {
    private static ProxyFactory proxyFactory = new ProxyFactory();

    public static ProxyFactory getInstance() {
        return proxyFactory;
    }



    /**
     * Jdk动态代理
     * @param obj  委托对象
     * @return   代理对象
     */
    public Object getJdkProxy(Object obj) {

        // 获取代理对象
        return  Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(),
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        Object result = null;

                        try{
                            //权限校验 (循环参数，获取)
                            HttpServletRequest req = (HttpServletRequest) args[0];
                            HttpServletResponse resp = (HttpServletResponse) args[1];
//                            boolean check = checkAuthorityService.checkHasAuthority(req.getRequestURI() ,(String) args[2]);
                            //权限校验
                            String[] names = null;

                            //判断该类是否有Security 权限校验注解
                            Class oClazz = obj.getClass();
                            if(oClazz.isAnnotationPresent(LagouSecurity.class)){
                                //获取注解value值
                                LagouSecurity annotation = (LagouSecurity) oClazz.getAnnotation(LagouSecurity.class);
                                //获取注解value值
                                names = annotation.value();

                            }
                            //类上面没有，再判断该handler是否有Security注解
                            else if(method.isAnnotationPresent(LagouSecurity.class)){
                                //获取注解value值
                                LagouSecurity annotation = (LagouSecurity) method.getAnnotation(LagouSecurity.class);
                                //获取注解value值
                                names = annotation.value();
                            }
                            if(names != null && names.length > 0){
                                boolean flag = false;
                                for(String name : names){
                                    if(name.equals(args[2])){
                                        flag = true;
                                    }
                                }
                                if(!flag){
                                    resp.getWriter().write("No current user name security");
                                    return false;
                                }
                            }
                            result = method.invoke(obj,args);
                        }catch (Exception e) {
                            e.printStackTrace();
                            throw e;

                        }

                        return result;
                    }
                });

    }


    /**
     * 使用cglib动态代理生成代理对象
     * @param obj 委托对象
     * @return
     */
    public Object getCglibProxy(Object obj) {
        return  Enhancer.create(obj.getClass(), new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                Object result = null;
                try{
                    //权限校验 (循环参数，获取)
                    HttpServletRequest req = (HttpServletRequest) objects[0];
                    HttpServletResponse resp = (HttpServletResponse) objects[1];
//                            boolean check = checkAuthorityService.checkHasAuthority(req.getRequestURI() ,(String) args[2]);
                    //权限校验
                    String[] names = null;

                    //判断该类是否有Security 权限校验注解
                    Class oClazz = obj.getClass();
                    if(oClazz.isAnnotationPresent(LagouSecurity.class)){
                        //获取注解value值
                        LagouSecurity annotation = (LagouSecurity) oClazz.getAnnotation(LagouSecurity.class);
                        //获取注解value值
                        names = annotation.value();

                    }
                    //类上面没有，再判断该handler是否有Security注解
                    else if(method.isAnnotationPresent(LagouSecurity.class)){
                        //获取注解value值
                        LagouSecurity annotation = (LagouSecurity) method.getAnnotation(LagouSecurity.class);
                        //获取注解value值
                        names = annotation.value();
                    }
                    if(names != null && names.length > 0){
                        boolean flag = false;
                        for(String name : names){
                            if(name.equals(objects[2])){
                                flag = true;
                            }
                        }
                        if(!flag){
                            resp.getWriter().write("No current user name security");
                            return false;
                        }
                    }

                    result = method.invoke(obj,objects);


                }catch (Exception e) {
                    e.printStackTrace();


                    // 抛出异常便于上层servlet捕获
                    throw e;

                }
                return result;
            }
        });
    }
}
